package cn.yuanqiao.web.controller.activiti;

import cn.yuanqiao.activiti.aspect.AddApprovalGroup;
import cn.yuanqiao.activiti.domain.*;
import cn.yuanqiao.activiti.listener.GetNextAssigneeListener;
import cn.yuanqiao.activiti.mapper.YqdaWorkflowArchiveSaveMapper;
import cn.yuanqiao.activiti.service.*;
import cn.yuanqiao.activiti.util.SecurityUtil;
import cn.yuanqiao.activiti.util.UuidUtil;
import cn.yuanqiao.common.constant.HttpStatus;
import cn.yuanqiao.common.core.controller.BaseController;
import cn.yuanqiao.common.core.domain.AjaxResult;
import cn.yuanqiao.common.core.domain.R;
import cn.yuanqiao.common.core.domain.entity.SysUser;
import cn.yuanqiao.common.core.domain.model.LoginUser;
import cn.yuanqiao.common.core.page.PageDomain;
import cn.yuanqiao.common.core.page.TableDataInfo;
import cn.yuanqiao.common.core.page.TableSupport;
import cn.yuanqiao.common.exception.activiti.ArchiveProcessException;
import cn.yuanqiao.common.utils.DateUtils;
import cn.yuanqiao.common.utils.SecurityUtils;
import cn.yuanqiao.common.utils.SnowflakeIdGenerator;
import cn.yuanqiao.common.utils.file.FileUtils;
import cn.yuanqiao.system.domain.SysFile;
import cn.yuanqiao.system.service.ISysUserService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import org.activiti.api.process.model.ProcessDefinition;
import org.activiti.api.process.model.builders.ProcessPayloadBuilder;
import org.activiti.api.process.runtime.ProcessRuntime;
import org.activiti.api.runtime.shared.query.Pageable;
import org.activiti.api.task.model.Task;
import org.activiti.api.task.model.builders.TaskPayloadBuilder;
import org.activiti.api.task.runtime.TaskRuntime;
import org.activiti.engine.*;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @ClassName: ActivitiApiController
 * @Description: activiti抽象出api接口
 * @author: lihuahua
 * @date: 2023/6/12 15:14
 * @Blog: huahuacoco.top
 */
@RestController
@RequestMapping("/activiti/activitiApiController")
public class ActivitiApiController extends BaseController {


    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private IActTaskService actTaskService;

    @Autowired
    private SecurityUtil securityUtil;

    @Autowired
    private YqdaWorkflowArchiveSaveMapper yqdaWorkflowArchiveSaveMapper;

    @Autowired
    private ISysFileService sysFileService;

    @Autowired
    private ProcessRuntime processRuntime;

    @Autowired
    private ProcessEngine processEngine;

    @Autowired
    private HistoryService historyService;

    @Autowired
    private TaskRuntime taskRuntime;

    @Autowired
    private IActConFormService actConFormService;

    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private IActArchiveDataService actArchiveDataService;

    @Autowired
    private ISysUserService sysUserService;


    @Autowired
    private IActWorkflowFormDataService actWorkflowFormDataService;

    @Autowired
    private IYqdaWorkflowArchiveSaveService yqdaWorkflowArchiveSaveService;

    @PostMapping("/startProcessInstance/{processName}")
    public R<ActivitiPackage> startProcessInstance(@PathVariable("processName") String processName, @RequestBody Map<String, Object> variables){
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUser.getUser();
        securityUtil.logInAs(sysUser);
        String id = UuidUtil.getShortUuid();
        //启动流程实例
        /*ProcessInstance processInstance = processRuntime.start(ProcessPayloadBuilder
                .start()
                .withProcessDefinitionKey(processName)
                .withName(processName)
                .withBusinessKey(id)
                .withVariables(variables)
                .build());*/
        ProcessInstance processInstance = processEngine.getRuntimeService()
                .createProcessInstanceBuilder()
                .processDefinitionKey(processName)
                .tenantId(sysUser.getTenantCode())
                .name(processName)
                .variables(variables).start();
        return R.ok(new ActivitiPackage(processInstance));
    }


    @PostMapping("/getFormCodeByBusinessKey/{businessKey}/{tenantCode}")
    public R<String> getFormCodeByBusinessKey(@PathVariable("businessKey") String businessKey, @PathVariable("tenantCode")String tenantCode){
        String formCode = actConFormService.getFormCodeByBussinessKey(businessKey,tenantCode);
        return R.ok(formCode);
    }


    /**
     * 文书档案归档流程
     * @param variables 表单参数
     * @return
     */
    @AddApprovalGroup
    @PostMapping("/startProcessInstance/WS_Archive_Save")
    public R<ActivitiPackage> startProcessWsArchiveSave(@RequestBody Map<String, Object> variables){
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUser.getUser();
        securityUtil.logInAs(sysUser);
        String id = UuidUtil.getShortUuid();
        List<Map<String,Object>> archiveData = (List<Map<String,Object>>)variables.get("archiveData");
        if (archiveData == null){
            throw new ArchiveProcessException("档案数据不能为空");
        }
        //启动流程实例

        ProcessInstance processInstance = processEngine.getRuntimeService()
                .createProcessInstanceBuilder()
                .processDefinitionKey("WS_Archive_Save")
                .tenantId(sysUser.getTenantCode())
                .name("("+sysUser.getNickName()+")档案归档流程")
                .businessKey(id)
                .variables(variables).start();
        List<ActArchiveData> archiveDataList = new ArrayList<>();
        for (Map<String, Object> item:archiveData){
            ActArchiveData actArchiveData = new ActArchiveData();
            actArchiveData.setActivitiKey("WS_Archive_Save");
            actArchiveData.setDeployId(processInstance.getId());
            actArchiveData.setArchiveId(item.get("ID").toString());
            actArchiveData.setCreateTime(DateUtils.getNowDate());
            actArchiveData.setSTATE("1"/*start.getStatus().equals(ProcessInstance.ProcessInstanceStatus.RUNNING)?"1":"2"*/);
            archiveDataList.add(actArchiveData);
        }

        actArchiveDataService.batchInsertActArchiveData(archiveDataList);
        return R.ok(new ActivitiPackage(processInstance));
    }

    /**
     * 文书档案借阅流程
     * @param variables 表单参数
     * @return
     */
    @AddApprovalGroup
    @PostMapping("/startProcessInstance/WorkFlow_Archive_Borrow")
    public R<ActivitiPackage> startProcessWsArchiveBorrow(@RequestBody Map<String, Object> variables){
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUser.getUser();
        securityUtil.logInAs(sysUser);
        String id = String.valueOf(SnowflakeIdGenerator.generateId());
        List<Map<String,Object>> archiveData = (List<Map<String,Object>>)variables.get("archiveData");
        if (archiveData == null){
            throw new ArchiveProcessException("档案数据不能为空");
        }
        //启动流程实例
        /*ProcessInstance processInstance = processRuntime.start(ProcessPayloadBuilder
                .start()
                .withProcessDefinitionKey("WorkFlow_Archive_Borrow")
                .withName("文书档案借阅流程")
                .withBusinessKey(id)
                .withVariables(variables)
                .build());*/
        YqdaWorkflowArchiveSave yqdaWorkflowArchiveSave = new YqdaWorkflowArchiveSave();
        Authentication.setAuthenticatedUserId(sysUser.getUserName());
        ProcessInstance processInstance = processEngine.getRuntimeService()
                .createProcessInstanceBuilder()
                .processDefinitionKey("WorkFlow_Archive_Borrow")
                .tenantId(sysUser.getTenantCode())
                .businessKey(id)
                .name("("+sysUser.getNickName()+")档案借阅流程")
                .variables(variables).start();
        //processEngine.getRuntimeServic.createMembership("2", "财务组");
        yqdaWorkflowArchiveSave.setID(id);
        yqdaWorkflowArchiveSave.setCreateTime(DateUtils.getNowDate());
        yqdaWorkflowArchiveSave.setInstanceId(processInstance.getId());
        yqdaWorkflowArchiveSave.setSTATE("0");
        yqdaWorkflowArchiveSave.setTITLE("档案借阅流程");
        yqdaWorkflowArchiveSave.setCreateName(sysUser.getNickName());
        yqdaWorkflowArchiveSave.setCreateBy(SecurityUtils.getUsername());
        yqdaWorkflowArchiveSave.setCreateTime(DateUtils.getNowDate());
        yqdaWorkflowArchiveSave.setCreateTime(DateUtils.getNowDate());
        yqdaWorkflowArchiveSaveService.addYqdaWorkflowArchiveSave(yqdaWorkflowArchiveSave);
        List<ActArchiveData> archiveDataList = new ArrayList<>();
        for (Map<String, Object> item:archiveData){
            ActArchiveData actArchiveData = new ActArchiveData();
            actArchiveData.setActivitiKey("WorkFlow_Archive_Borrow");
            actArchiveData.setDeployId(processInstance.getId());
            actArchiveData.setArchiveId(item.get("ID").toString());
            actArchiveData.setSTATE("1"/*processInstance.getStatus().equals(ProcessInstance.ProcessInstanceStatus.RUNNING)?"1":"2"*/);
            actArchiveData.setCreateTime(DateUtils.getNowDate());
            archiveDataList.add(actArchiveData);
        }

        //actArchiveDataService.batchInsertActArchiveData(archiveDataList);
        return R.ok(new ActivitiPackage(processInstance));
    }

    /**
     * 文书档案借阅流程
     * @param variables 表单参数
     * @return
     */
    @AddApprovalGroup
    @PostMapping("/startProcessInstance/WorkFlow_Archive_HandOver")
    public R<ActivitiPackage> startProcessWorkFlowArchiveHandOver(@RequestBody Map<String, Object> variables){
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUser.getUser();
        securityUtil.logInAs(sysUser);
        String id = UuidUtil.getShortUuid();
        Map<String,Object> handOverData = (Map<String,Object>)variables.get("processVariables");
        if (handOverData == null){
            throw new ArchiveProcessException("移交单数据不能为空");
        }
        ProcessInstance processInstance = processEngine.getRuntimeService()
                .createProcessInstanceBuilder()
                .processDefinitionKey("WorkFlow_Archive_HandOver")
                .tenantId(sysUser.getTenantCode())
                .businessKey(id)
                .name("("+sysUser.getNickName()+")档案移交流程")
                .variables(variables).start();
        //actArchiveDataService.batchInsertActArchiveData(archiveDataList);
        return R.ok(new ActivitiPackage(processInstance));
    }

    /**
     * 获取流程状态
     * @param archiveId 表单参数
     * @return
     */
    @PostMapping("/getProcessState/{archiveId}")
    public R<ActivitiPackage> getProcessState(@PathVariable("archiveId") String archiveId){
        ActArchiveData actArchiveData = new ActArchiveData(archiveId);
        List<ActArchiveData> archiveDataList = actArchiveDataService.selectActArchiveDataList(actArchiveData);
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUser.getUser();
        securityUtil.logInAs(sysUser);
        //启动流程实例1
        /*List<ProcessInstance> processInstanceList = new ArrayList<>();
        for (ActArchiveData item:archiveDataList) {
            ProcessInstance processInstance = processRuntime.processInstance(item.getDeployId());
            System.out.println(111);
            if (processInstance!=null && processInstance.getStatus().equals(ProcessInstance.ProcessInstanceStatus.RUNNING)){
                processInstanceList.add(processInstance);
            }
        }
        return R.ok(new ActivitiPackage(processInstanceList));*/
        List<ProcessInstance> processInstanceList = new ArrayList<>();
        RuntimeService runtimeService = processEngine.getRuntimeService();

        for (ActArchiveData item : archiveDataList) {
            ProcessInstance processInstance = runtimeService.createProcessInstanceQuery()
                    .processInstanceId(item.getDeployId())
                    .singleResult();

            if (processInstance != null && processInstance.isSuspended()) {
                processInstanceList.add(processInstance);
            }
        }

        return R.ok(new ActivitiPackage(processInstanceList));
    }


    @PostMapping("/completeProcessInstance/{processId}")
    public R<ActivitiPackage> complateProcessInstance(@PathVariable("processId") String processId, @RequestBody Map<String, Object> variables){
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUser.getUser();
        securityUtil.logInAs(sysUser);
        org.activiti.engine.task.Task task = taskService.createTaskQuery().processInstanceId(processId).active().singleResult();
        //获取当前用户的流程代办任务，并插入数据办理
        processRuntime.setVariables(ProcessPayloadBuilder.setVariables()
                .withVariables(variables).withProcessInstanceId(processId).build());
        Task complete = taskRuntime.complete(TaskPayloadBuilder.complete().withTaskId(task.getId())
                .withVariables(variables)
                .build());
        ActivitiPackage activitiPackage = new ActivitiPackage();
        activitiPackage.setTask(complete);
        return R.ok(activitiPackage);
    }


    public R<List<Map<String, Object>>> getTaskSummaryForUserOld() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUser.getUser();
        securityUtil.logInAs(sysUser);

        List<Map<String, Object>> result = new ArrayList<>();

        // 流程类型列表
        List<String> leixings = new ArrayList<>();
        leixings.add("product");
        leixings.add("待办");
        leixings.add("在办");
        leixings.add("已办");

        // 查询当前登录用户的待办任务
        List<Task> todoTasks = taskRuntime.tasks(Pageable.of(0, Integer.MAX_VALUE))
                .getContent()
                .stream()
                .collect(Collectors.toList());

        // 查询当前登录用户的已办任务
        List<HistoricTaskInstance> historicTasks = historyService.createHistoricTaskInstanceQuery()
                .finished() // 已完成的历史任务
                .list();

        long count = historyService.createHistoricTaskInstanceQuery()
                .finished() // 已完成的历史任务
                .processDefinitionKey("WS_Archive_Save").count();

        // 统计各个流程类型的待办和已办任务数量
        Map<String, Map<String, Integer>> taskSummary = new HashMap<>();
        for (Task task : todoTasks) {
            //ProcessInstance processInstance = processRuntime.processInstance(task.getProcessInstanceId());
            ProcessInstance processInstance = processEngine.getRuntimeService().createProcessInstanceQuery()
                    .processInstanceId(task.getProcessInstanceId())
                    .singleResult();
            String processDefinitionKey = processInstance.getProcessDefinitionKey();
            ProcessDefinition processDefinition = processRuntime.processDefinition(processDefinitionKey);
            String processName = processDefinition.getName();

            taskSummary.computeIfAbsent(processName==null?processDefinitionKey:processName, k -> new HashMap<>())
                    .merge("待办", 1, Integer::sum);
        }

        for (HistoricTaskInstance task : historicTasks) {
            List<HistoricTaskInstance> historicTaskInstances = historyService.createHistoricTaskInstanceQuery().processInstanceId(task.getProcessInstanceId()).list();
            String processDefinitionKey = historicTaskInstances.get(0).getProcessDefinitionId().split(":")[0];
            ProcessDefinition processDefinition = processRuntime.processDefinition(processDefinitionKey);
            String processName = processDefinition.getName();
            taskSummary.computeIfAbsent(processName==null?processDefinitionKey:processName, k -> new HashMap<>())
                    .merge("已办", 1, Integer::sum);
        }

        // 构建结果数据结构
        for (String processDefinitionKey : taskSummary.keySet()) {
            Map<String, Object> item = new HashMap<>();
            item.put("product", processDefinitionKey);
            item.put("待办", taskSummary.getOrDefault(processDefinitionKey, Collections.emptyMap()).getOrDefault("待办", 0));
            item.put("在办", 0); // 在办任务数量在 Activiti 中无法直接查询，需要根据具体业务逻辑来确定
            item.put("已办", taskSummary.getOrDefault(processDefinitionKey, Collections.emptyMap()).getOrDefault("已办", 0));
            result.add(item);
        }

        return R.ok(result);
    }

    @PostMapping("/getProcessCount")
    public R<List<Map<String, Object>>> getTaskSummaryForUser() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUser.getUser();
        securityUtil.logInAs(sysUser);

        List<Map<String, Object>> result = new ArrayList<>();

        // 流程类型列表
        List<String> leixings = Arrays.asList("product", "待办", "在办", "已办");

        // 查询当前登录用户的待办任务
        List<org.activiti.engine.task.Task> todoTasks = taskService.createTaskQuery()
                .taskAssignee(sysUser.getUserName())
                .taskTenantId(sysUser.getTenantCode())
                .list();

        // 查询当前登录用户的已办任务
        List<HistoricTaskInstance> historicTasks = historyService.createHistoricTaskInstanceQuery()
                .taskAssignee(sysUser.getUserName())
                .taskTenantId(sysUser.getTenantCode())
                .finished() // 已完成的历史任务
                .list();

        // 统计各个流程类型的待办和已办任务数量
        Map<String, Map<String, Integer>> taskSummary = new HashMap<>();
        for (org.activiti.engine.task.Task task : todoTasks) {
            ProcessInstance processInstance = runtimeService.createProcessInstanceQuery()
                    .processInstanceId(task.getProcessInstanceId())
                    .singleResult();
            if (processInstance == null){continue;}
            String processDefinitionKey = processInstance.getProcessDefinitionKey();
            String processName = processInstance.getProcessDefinitionName();

            taskSummary.computeIfAbsent(processName == null ? processDefinitionKey : processName, k -> new HashMap<>())
                    .merge("待办", 1, Integer::sum);
        }

        for (HistoricTaskInstance task : historicTasks) {
            List<HistoricTaskInstance> historicTaskInstances = historyService.createHistoricTaskInstanceQuery()
                    .processInstanceId(task.getProcessInstanceId())
                    .taskTenantId(sysUser.getTenantCode())
                    .list();
            String processDefinitionKey = historicTaskInstances.get(0).getProcessDefinitionId().split(":")[0];
            String processName = historicTaskInstances.get(0).getName();

            taskSummary.computeIfAbsent(processName == null ? processDefinitionKey : processName, k -> new HashMap<>())
                    .merge("已办", 1, Integer::sum);
        }

        // 构建结果数据结构
        for (String processDefinitionKey : taskSummary.keySet()) {
            Map<String, Object> item = new HashMap<>();
            item.put("product", processDefinitionKey);
            item.put("待办", taskSummary.getOrDefault(processDefinitionKey, Collections.emptyMap()).getOrDefault("待办", 0));
            item.put("在办", 0); // 在办任务数量在 Activiti 中无法直接查询，需要根据具体业务逻辑来确定
            item.put("已办", taskSummary.getOrDefault(processDefinitionKey, Collections.emptyMap()).getOrDefault("已办", 0));
            result.add(item);
        }

        return R.ok(result);
    }

    //获取我的代办任务
    @GetMapping(value = "/getAllProcessCount")
    public AjaxResult getTasks() {

        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUser.getUser();
        securityUtil.logInAs(sysUser);
        int todoTaskCount = taskService.createTaskQuery().taskTenantId(sysUser.getTenantCode())
                .taskAssignee(sysUser.getUserName()).list().size();
                /*.tasks(Pageable.of(0, Integer.MAX_VALUE))
                .getContent()
                .stream()
                .count();*/
        return AjaxResult.success("查询成功",todoTaskCount);
    }

    //获取所有流程key和对应的中文名
    @GetMapping(value = "/getProcessKeyName")
    public AjaxResult getProcessKeyName() {
        List<org.activiti.engine.repository.ProcessDefinition> processDefinitions = repositoryService.createProcessDefinitionQuery().processDefinitionTenantId(SecurityUtils.getTenantCode()).list();
        Map<String, String> processKeyMap = new HashMap<>();

        for (org.activiti.engine.repository.ProcessDefinition processDefinition : processDefinitions) {
            processKeyMap.put(processDefinition.getKey(), processDefinition.getName());
        }

        return AjaxResult.success(processKeyMap);
    }

    @Autowired
    private GetNextAssigneeListener getNextAssigneeListener;

    //通过taskId获取流程实例，并返回流程中每个节点的办理人和办理结果
    @GetMapping(value = "/getProcessDate/{taskId}")
    public AjaxResult getProcessDate(@PathVariable("taskId") String taskId) {

        org.activiti.engine.task.Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        List<Map<String, Object>> resultList = new ArrayList<>();
        Map<String, Object> stringListMap = null;
        try {
            stringListMap = getNextAssigneeListener.nextPrcessApprover(task.getProcessInstanceId(), task.getProcessDefinitionId(), task);
            //resultList.add(stringListMap);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 查询历史任务实例
        List<HistoricTaskInstance> historicTaskInstances = historyService.createHistoricTaskInstanceQuery()
                .taskId(taskId)
                .orderByHistoricTaskInstanceStartTime()
                .asc()
                .list();

        for (HistoricTaskInstance historicTask : historicTaskInstances) {
            Map<String, Object> taskInfo = new HashMap<>();
            if (stringListMap!=null) {taskInfo.putAll(stringListMap);}
            taskInfo.put("taskName", historicTask.getName());
            taskInfo.put("assignee", historicTask.getAssignee());

            // 查询历史活动实例，即流程中每个节点的执行信息
            List<HistoricActivityInstance> historicActivityInstances = historyService.createHistoricActivityInstanceQuery()
                    .processInstanceId(historicTask.getProcessInstanceId())
                    .orderByHistoricActivityInstanceStartTime()
                    .asc()
                    .list();

            List<Map<String, Object>> activityList = new ArrayList<>();
            for (HistoricActivityInstance activityInstance : historicActivityInstances) {
                if (!activityInstance.getActivityType().equals("userTask")) continue;
                Map<String, Object> activityInfo = new HashMap<>();
                activityInfo.put("activityName", activityInstance.getActivityName());
                activityInfo.put("assignee", activityInstance.getAssignee());
                SysUser sysUser = sysUserService.selectUserByUserName(activityInstance.getAssignee());
                if (sysUser!=null){
                    activityInfo.put("userName",sysUser.getNickName());
                }
                activityInfo.put("startTime", activityInstance.getStartTime());
                activityInfo.put("endTime", activityInstance.getEndTime());
                //String instanceId = actArchiveDataService.getBusinessIdFromWorkFlowArchiveSaveByInstanceId(historicTask.getProcessInstanceId());
                List<ActWorkflowFormData> actWorkflowFormData = actWorkflowFormDataService.selectActWorkflowFormDataByBusinessKey(activityInstance.getTaskId());
                List<Map<String, Object>> mapList = new ArrayList<>();
                activityInfo.put("isAgree", activityInstance);
                activityInfo.put("comment", null);

                /*actWorkflowFormData.stream()
                        .map(ActWorkflowFormData::toProcessMap) // 调用每个实例的 toProcessMap 方法
                        .collect(Collectors.toList()); // 将转换后的 Map 收集为 List*/

                for (ActWorkflowFormData workFlowFormData : actWorkflowFormData) {
                    if ("is_agree".equals(workFlowFormData.getControlId())){
                        activityInfo.put("isAgree", workFlowFormData.toProcessMap());
                    }else if ("comment".equals(workFlowFormData.getControlId())){
                        activityInfo.put("comment", workFlowFormData.toProcessMap());
                    }else {
                        mapList.add(workFlowFormData.toProcessMap());
                    }
                }
                activityInfo.put("otherVariables", mapList);
                // 查询节点的审批意见
               /* List<Comment> comments = taskService.getTaskComments(activityInstance.getTaskId());
                List<String> commentList = new ArrayList<>();
                for (Comment comment : comments) {
                    commentList.add(comment.getFullMessage());
                }
                activityInfo.put("comments", commentList);*/

                activityList.add(activityInfo);
            }

            taskInfo.put("activityList", activityList);
            resultList.add(taskInfo);
        }

        return AjaxResult.success(resultList);
    }

    //通过taskId获取流程实例，并返回流程中每个节点的办理人和办理结果
    @GetMapping(value = "/getProcessDateByInstanceId/{instanceId}")
    public AjaxResult getProcessDateByInstanceId(@PathVariable("instanceId") String instanceId) {
        List<Map<String, Object>> resultList = new ArrayList<>();

        // 查询历史任务实例
        List<HistoricTaskInstance> historicTaskInstances = historyService.createHistoricTaskInstanceQuery()
                .processInstanceId(instanceId)
                .orderByHistoricTaskInstanceStartTime()
                .asc()
                .list();

        for (HistoricTaskInstance historicTask : historicTaskInstances) {
            Map<String, Object> taskInfo = new HashMap<>();
            taskInfo.put("taskName", historicTask.getName());
            taskInfo.put("assignee", historicTask.getAssignee());

            // 查询历史活动实例，即流程中每个节点的执行信息
            List<HistoricActivityInstance> historicActivityInstances = historyService.createHistoricActivityInstanceQuery()
                    .processInstanceId(historicTask.getProcessInstanceId())
                    .orderByHistoricActivityInstanceStartTime()
                    .asc()
                    .list();

            List<Map<String, Object>> activityList = new ArrayList<>();
            for (HistoricActivityInstance activityInstance : historicActivityInstances) {
                if (!activityInstance.getActivityType().equals("userTask")) continue;
                Map<String, Object> activityInfo = new HashMap<>();
                activityInfo.put("activityName", activityInstance.getActivityName());
                activityInfo.put("assignee", activityInstance.getAssignee());
                if(activityInstance.getAssignee()==null){
                    continue;
                }
                SysUser sysUser = sysUserService.selectUserByUserName(activityInstance.getAssignee());
                activityInfo.put("userName",sysUser.getNickName());
                activityInfo.put("startTime", activityInstance.getStartTime());
                activityInfo.put("endTime", activityInstance.getEndTime());
                //String bussKey = actArchiveDataService.getBusinessIdFromWorkFlowArchiveSaveByInstanceId(historicTask.getProcessInstanceId());
                List<ActWorkflowFormData> actWorkflowFormData = actWorkflowFormDataService.selectActWorkflowFormDataByBusinessKey(activityInstance.getTaskId());
                List<Map<String, Object>> mapList = new ArrayList<>();
                activityInfo.put("isAgree", activityInstance);
                activityInfo.put("comment", null);

                /*actWorkflowFormData.stream()
                        .map(ActWorkflowFormData::toProcessMap) // 调用每个实例的 toProcessMap 方法
                        .collect(Collectors.toList()); // 将转换后的 Map 收集为 List*/

                for (ActWorkflowFormData workFlowFormData : actWorkflowFormData) {
                    if ("is_agree".equals(workFlowFormData.getControlId())){
                        activityInfo.put("isAgree", workFlowFormData.toProcessMap());
                    }else if ("comment".equals(workFlowFormData.getControlId())){
                        activityInfo.put("comment", workFlowFormData.toProcessMap());
                    }else {
                        mapList.add(workFlowFormData.toProcessMap());
                    }
                }
                activityInfo.put("otherVariables", mapList);
                // 查询节点的审批意见
               /* List<Comment> comments = taskService.getTaskComments(activityInstance.getTaskId());
                List<String> commentList = new ArrayList<>();
                for (Comment comment : comments) {
                    commentList.add(comment.getFullMessage());
                }
                activityInfo.put("comments", commentList);*/

                activityList.add(activityInfo);
            }

            taskInfo.put("activityList", activityList);
            resultList.add(taskInfo);
        }

        return AjaxResult.success(resultList);
    }

    //通过taskId获取流程实例，并返回流程中每个节点的办理人和办理结果
    @GetMapping(value = "/getProcessDateByProcessId/{processId}")
    public R<List<Map<String, Object>>> getProcessDateByProcessId(@PathVariable("processId") String processId) {
            // 查询历史活动实例，即流程中每个节点的执行信息
            List<HistoricActivityInstance> historicActivityInstances = historyService.createHistoricActivityInstanceQuery()
                    .processInstanceId(processId)
                    .orderByHistoricActivityInstanceStartTime()
                    .asc()
                    .list();

            List<Map<String, Object>> activityList = new ArrayList<>();
            for (HistoricActivityInstance activityInstance : historicActivityInstances) {
                if (!activityInstance.getActivityType().equals("userTask")) continue;
                Map<String, Object> activityInfo = new HashMap<>();
                activityInfo.put("activityName", activityInstance.getActivityName());
                activityInfo.put("assignee", activityInstance.getAssignee());
                activityInfo.put("startTime", activityInstance.getStartTime());
                SysUser sysUser = sysUserService.selectUserByUserName(activityInstance.getAssignee());
                activityInfo.put("userName",sysUser == null ? "":sysUser.getNickName());
                activityInfo.put("endTime", activityInstance.getEndTime());
                //String instanceId = actArchiveDataService.getBusinessIdFromWorkFlowArchiveSaveByInstanceId(processId);
                List<ActWorkflowFormData> actWorkflowFormData = actWorkflowFormDataService.selectActWorkflowFormDataByBusinessKey(activityInstance.getTaskId());
                List<Map<String, Object>> mapList = new ArrayList<>();
                activityInfo.put("isAgree", null);
                activityInfo.put("comment", null);

                /*actWorkflowFormData.stream()
                        .map(ActWorkflowFormData::toProcessMap) // 调用每个实例的 toProcessMap 方法
                        .collect(Collectors.toList()); // 将转换后的 Map 收集为 List*/

                for (ActWorkflowFormData workFlowFormData : actWorkflowFormData) {
                    if ("is_agree".equals(workFlowFormData.getControlId())){
                        activityInfo.put("isAgree", workFlowFormData.toProcessMap());
                    }else if ("comment".equals(workFlowFormData.getControlId())){
                        activityInfo.put("comment", workFlowFormData.toProcessMap());
                    }else {
                        mapList.add(workFlowFormData.toProcessMap());
                    }
                }
                activityInfo.put("otherVariables", mapList);
                // 查询节点的审批意见
               /* List<Comment> comments = taskService.getTaskComments(activityInstance.getTaskId());
                List<String> commentList = new ArrayList<>();
                for (Comment comment : comments) {
                    commentList.add(comment.getFullMessage());
                }
                activityInfo.put("comments", commentList);*/

                activityList.add(activityInfo);
            }

        return R.ok(activityList);
    }

    @PostMapping("/endWorkFlowInstance/{reason}/{instanceId}")
    R<Boolean> endWorkFlowInstance(@PathVariable("reason")String reason, @PathVariable("instanceId")String instanceId){
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUser.getUser();
        securityUtil.logInAs(sysUser);
        processRuntime.delete(ProcessPayloadBuilder
                .delete()
                .withProcessInstanceId(instanceId)
                .withReason(reason)
                .build());
        return R.ok(true);
    }

    /**
     * WorkFlow_Archive_MJIdentify
     */

    /**
     * 文书档案归档流程
     * @param variables 表单参数
     * @return
     */
    @PostMapping("/startProcessInstance/WorkFlowArchiveMJIdentify")
    public R<ActivitiPackage> startProcessWsArchiveMJIdentify(@RequestBody Map<String, Object> variables){
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUser.getUser();
        securityUtil.logInAs(sysUser);
        String id = String.valueOf(SnowflakeIdGenerator.generateId());
        /*List<Map<String,Object>> archiveData = (List<Map<String,Object>>)variables.get("archiveData");
        if (archiveData == null){
            throw new ArchiveProcessException("档案数据不能为空");
        }*/
        YqdaWorkflowArchiveSave yqdaWorkflowArchiveSave = new YqdaWorkflowArchiveSave();
        yqdaWorkflowArchiveSave.setID(id);
        ProcessInstance processInstance = processEngine.getRuntimeService()
                .createProcessInstanceBuilder()
                .processDefinitionKey("WorkFlow_Archive_MJIdentify")
                .tenantId(sysUser.getTenantCode())
                .name("("+sysUser.getNickName()+")档案密级鉴定流程")
                .businessKey(id)
                .variables(variables).start();
        yqdaWorkflowArchiveSave.setInstanceId(processInstance.getId());
        yqdaWorkflowArchiveSave.setSTATE("0");
        yqdaWorkflowArchiveSave.setTITLE("档案密级鉴定流程");
        yqdaWorkflowArchiveSave.setCreateName(sysUser.getNickName());
        yqdaWorkflowArchiveSave.setCreateBy(SecurityUtils.getUsername());
        yqdaWorkflowArchiveSave.setCreateTime(DateUtils.getNowDate());
        yqdaWorkflowArchiveSave.setCreateTime(DateUtils.getNowDate());
        yqdaWorkflowArchiveSaveMapper.insertYqdaWorkflowArchiveSave(yqdaWorkflowArchiveSave);
        return R.ok(new ActivitiPackage(processInstance));
    }

    /**
     * 保管期限鉴定流程
     * @param variables 表单参数
     * @return
     */
    @PostMapping("/startProcessInstance/WorkFlowArchiveBGQXIdentify")
    public R<ActivitiPackage> startProcessWsArchiveBGQXIdentify(@RequestBody Map<String, Object> variables){
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUser.getUser();
        securityUtil.logInAs(sysUser);
        String id = String.valueOf(SnowflakeIdGenerator.generateId());
        /*List<Map<String,Object>> archiveData = (List<Map<String,Object>>)variables.get("archiveData");
        if (archiveData == null){
            throw new ArchiveProcessException("档案数据不能为空");
        }*/
        YqdaWorkflowArchiveSave yqdaWorkflowArchiveSave = new YqdaWorkflowArchiveSave();
        yqdaWorkflowArchiveSave.setID(id);
        ProcessInstance processInstance = processEngine.getRuntimeService()
                .createProcessInstanceBuilder()
                .processDefinitionKey("WorkFlow_Archive_BGQXIdentify")
                .tenantId(sysUser.getTenantCode())
                .name("("+sysUser.getNickName()+")档案保管期限鉴定流程")
                .businessKey(id)
                .variables(variables).start();
        yqdaWorkflowArchiveSave.setInstanceId(processInstance.getId());
        yqdaWorkflowArchiveSave.setSTATE("0");
        yqdaWorkflowArchiveSave.setTITLE("档案保管期限鉴定流程");
        yqdaWorkflowArchiveSave.setCreateName(sysUser.getNickName());
        yqdaWorkflowArchiveSave.setCreateBy(SecurityUtils.getUsername());
        yqdaWorkflowArchiveSave.setCreateTime(DateUtils.getNowDate());
        yqdaWorkflowArchiveSave.setCreateTime(DateUtils.getNowDate());
        yqdaWorkflowArchiveSaveMapper.insertYqdaWorkflowArchiveSave(yqdaWorkflowArchiveSave);
        return R.ok(new ActivitiPackage(processInstance));
    }

    /**
     * 文书档案归档流程
     * @param processId 流程id
     * @return
     */
    @PostMapping("/getTaskByInstanceId/{processId}")
    public R<List<ActivitiPackage>> getTaskByInstanceId(@PathVariable("processId") String processId){
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUser.getUser();
        securityUtil.logInAs(sysUser);
        /*String id = UuidUtil.getShortUuid();
        *//*List<Map<String,Object>> archiveData = (List<Map<String,Object>>)variables.get("archiveData");
        if (archiveData == null){
            throw new ArchiveProcessException("档案数据不能为空");
        }*//*
        // 查询当前登录用户的待办任务
        List<Task> todoTasks = taskRuntime.tasks(Pageable.of(0, Integer.MAX_VALUE))
                .getContent()
                .stream()
                .filter(task -> task.getProcessInstanceId().equals(processId))
                .collect(Collectors.toList());*/

        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processId).singleResult();


        List<ActivitiPackage> actTaskDTOS =  taskRuntime.tasks(Pageable.of(0, Integer.MAX_VALUE))
                .getContent().stream()
                .filter(task -> task.getProcessInstanceId().equals(processId))
                .map(task -> new ActivitiPackage(task, processInstance))
                .collect(Collectors.toList());
        return R.ok(actTaskDTOS);
    }

    @PostMapping("/getTaskIdByProcessId/{processId}")
    public R<String> getTaskIdByProcessId(@PathVariable("processId") String processId){
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUser.getUser();
        securityUtil.logInAs(sysUser);
        String taskId =  taskRuntime.tasks(Pageable.of(0, Integer.MAX_VALUE))
                .getContent().stream()
                .filter(task -> task.getProcessInstanceId().equals(processId))
                .findAny().get().getId();
        return R.ok(taskId);
    }

    //获取我的代办任务
    @GetMapping(value = "/taskList/{workflowKey}")
    public TableDataInfo getTasks(@RequestParam(value = "instanceName",required = false) String instanceName, @PathVariable("workflowKey")String workflowKey) {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Page<ActTaskDTO> hashMaps = actTaskService.selectProcessDefinitionListByCode(pageDomain,workflowKey,instanceName);
        return getDataTable(hashMaps);
    }

    //获取我的代办任务
    @GetMapping(value = "/taskHistoryList/{workflowKey}")
    public TableDataInfo getTaskHistoryList(@RequestParam(value = "instanceName",required = false) String instanceName, @PathVariable("workflowKey")String workflowKey) {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Page<ActHistoryTaskDTO> hashMaps = actTaskService.selectProcessDefinitionListHistoyByCode(pageDomain,workflowKey,instanceName);
        return getDataTable(hashMaps);
    }

    //获取我的代办任务
    @GetMapping(value = "/getArchiveTotal/{isType}/{instanceId}")
    public R<Map<String,Object>> getArchiveTotal(@PathVariable(value = "isType") String isType, @PathVariable(value = "instanceId") String instanceId) {
        Map<String,Object> hashMaps = actTaskService.getArchiveTotal(isType,instanceId);
        return R.ok(hashMaps);
    }

    /**
     * 文件上传请求
     */
    @PostMapping("upload")
    public R<SysFile> upload(MultipartFile file)
    {
        try
        {
            // 上传并返回访问地址
            String url = sysFileService.uploadFile(file);
            SysFile sysFile = new SysFile();
            sysFile.setName(FileUtils.getName(url));
            sysFile.setUrl(url);
            return R.ok(sysFile);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return R.fail(e.getMessage());
        }
    }


    //获取我的代办任务
    @GetMapping(value = "/taskListByStartUser/{processKey}")
    public TableDataInfo getTaskListByStartUser(@RequestParam(value = "instanceName",required = false) String instanceName, @PathVariable("processKey") String processKey) {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Page<ActActivitiDTO> hashMaps = actTaskService.selectProcessDefinitionListHistoyByCodeAndStartUser(pageDomain,processKey,instanceName);
        return getDataTable(hashMaps);
    }






}
